package com.wanwu.channel.dao.datasource;

import com.wanwu.channel.common.enums.ExceptionEnum;
import com.wanwu.channel.common.exception.SystemException;
import com.wanwu.channel.common.util.LogUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

/**
 * Created by zhangyi on 2016/11/29.
 */
@Aspect
@Component
public class DataSourceAspect {

    private final static Logger log = LoggerFactory.getLogger(DataSourceAspect.class);

    @Around(value = "@annotation(dataSource)")
    public Object router(ProceedingJoinPoint joinPoint, DataSource dataSource) {
        try {
            DataSourceContextHolder.setDataSourceType(dataSource.value().name());
            return joinPoint.proceed();
        } catch (DuplicateKeyException | SystemException ex) {
            throw ex;
        } catch (Throwable ex) {
            LogUtil.error(log, ex, "数据源路由切面异常...");
            //todo
            throw new SystemException(ExceptionEnum.E10000);
        } finally {
            DataSourceContextHolder.clearDataSourceType();
        }
    }

}
